﻿@{
    // Cache the image for a minute
    Response.OutputCache(60);

    var galleryId = UrlData[0].AsInt();

    var db = Database.Open("PhotoGallery");

    var gallery = db.QuerySingle("SELECT * FROM Galleries WHERE Id = @0", galleryId);
    if (gallery == null) {
        Response.SetStatus(HttpStatusCode.NotFound);
        return;
    }

    var photos = db.Query("SELECT TOP(3) FileContents, UploadDate FROM Photos WHERE GalleryId = @0 ORDER BY UploadDate DESC", galleryId);
    if (photos.Count() == 0) {
        Response.Redirect("~/Images/gallery-empty.png");
        return;
    }

    using (var generator = new MultiThumbnailGenerator()) {
        foreach (var photo in photos) {
            using (var imageStream = new System.IO.MemoryStream(photo.FileContents)) {
                using (var image = System.Drawing.Image.FromStream(imageStream)) {
                    generator.AddImage(image);
                }
            }
        }
        using (var outStream = new System.IO.MemoryStream()) {
            generator.WritePngToStream(outStream);
            var image = new WebImage(outStream);
            image.Write();
        }
    }
}